/*
 * (C) Copyright 2005 Davide Brugali, Marco Torchiano
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 * 02111-1307  USA
 */

package model.environment;

/**
 * Title:        The MObile RObot Simulation Environment
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:      Universit� di Bergamo
 * @author Davide Brugali
 * @version 1.0
 */

import java.awt.*;
import java.awt.geom.Point2D;
import java.io.PrintWriter;
import java.util.ArrayList;

public abstract class Device implements Runnable {

	protected static final int STANDARD_DELAY = 20;

	// A final object to make sure the lock cannot be overwritten with another Object
	private final Object lock = new Object();

	private String name;                    // the name of this device
	protected Environment environment;        // a reference to the environment
	private Polygon shape;                  // the device's shape in local coords

	// a reference to the robot
	protected MobileRobot robot;
	// the robot current position
	protected Position robotPosition;
	// origin of the device reference frame with regards to the robot frame
	protected Position localPosition;

	private Color bgColor = Color.red;
	private Color fgColor = Color.blue;

	private Thread thread;
	private long delay;
	protected boolean running; // Is the device running?
	protected boolean executingCommand; // Is the device executingCommand a command?
	private ArrayList<String> commands;

	private PrintWriter output; //TODO: make a view or frame for this shit

	// the constructor
	public Device(String name, MobileRobot robot, Position local, Environment environment) {
		this.name = name;
		this.robot = robot;
		this.localPosition = local;
		this.environment = environment;
		robot.readPosition(this.robotPosition);

		this.shape = new Polygon();
		this.robotPosition = new Position();
		this.delay = Device.STANDARD_DELAY;

		this.running = false;
		this.executingCommand = false;

		this.commands = new ArrayList<String>();
		this.output = null;

		thread = new Thread(this);
	}

	// this method is invoked when the geometric shape of the device is defined
	protected void addPoint(int x, int y) {
		shape.addPoint(x, y);
	}

	// draws the device's geometric shape on the graphical interface
	public void paint(Graphics g) {
		// reads the robot's current position
		robot.readPosition(robotPosition);
		// draws the shape
		Polygon globalShape = new Polygon();
		Point2D point = new Point2D.Double();
		for (int i = 0; i < shape.npoints; i++) {
			point.setLocation(shape.xpoints[i], shape.ypoints[i]);
			// calculates the coordinates of the point according to the local position
			localPosition.rotateAroundAxis(point);
			// calculates the coordinates of the point according to the robot position
			robotPosition.rotateAroundAxis(point);
			// adds the point to the global shape
			globalShape.addPoint((int) Math.round(point.getX()), (int) Math.round(point.getY()));
		}
		g.setColor(bgColor);
		g.fillPolygon(globalShape);
		g.setColor(fgColor);
		g.drawPolygon(globalShape);
	}

	public boolean sendCommand(String command) {
		commands.add(command);
		synchronized (lock) {
			// Notify the tread that is waiting for commands.
			lock.notify();
		}
		return true;
	}

	public synchronized void writeOut(String data) {
		if (output != null) {
			output.println(data);
		} else {
			System.out.println(this.name + " output not initialized");
		}
	}

	public synchronized void start() {
		this.running = true;
		thread.start();

	}

	public synchronized void quit() {
		this.running = false;
		thread.interrupt();
	}

	public void setOutput(PrintWriter output) {
		this.output = output;
	}

	public void run() {
		System.out.println("Device " + this.name + " running");

		while (running) {
			try {
				if (executingCommand) {
					// pause before the next step
					synchronized (this) {
						Thread.sleep(delay);
					}
				} else if (commands.size() > 0) {
					// extracts the the next command and executes it
					String command = commands.remove(0);
					executeCommand(command);
				} else {
					// waits for a new command
					synchronized (lock) {
						// Wait to be notified about a new command (in sendCommand()).
						lock.wait();
					}
				}
				// processes a new step
				nextStep();
			} catch (InterruptedException ie) {
				System.err.println("Device : Run was interrupted.");
			}
		}
	}

	protected abstract void executeCommand(String command);

	protected abstract void nextStep();

}
